package com.jpa.demo.repository.factory;

import com.jpa.demo.repository.MyJpaRepository;
import com.jpa.demo.repository.support.MyEntityManager;
import com.jpa.demo.repository.support.MySimpleJpaRepository;

import java.io.Serializable;
import java.lang.reflect.*;

/**
 * 主要是为了产生代理类
 */
public class MyRepositoryFactory {

    private final MyEntityManager entityManager;

    public MyRepositoryFactory(MyEntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @SuppressWarnings("unchecked")
    public <T, ID extends Serializable> MyJpaRepository<T, ID> getRepository(Class<T> entityClass) {
        MySimpleJpaRepository<T, ID> repository = new MySimpleJpaRepository<>(entityClass, entityManager);

        //生成了一个代理类
        return (MyJpaRepository<T, ID>) Proxy.newProxyInstance(
                entityClass.getClassLoader(),
                new Class<?>[]{MyJpaRepository.class},
                new RepositoryInvocationHandler<>(repository)
        );
    }

    private static class RepositoryInvocationHandler<T, ID> implements InvocationHandler {

        private final MyJpaRepository<T, ID> target;

        public RepositoryInvocationHandler(MyJpaRepository<T, ID> target) {
            this.target = target;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            /**
             * method表示被调用的方法对象（被实现的接口的方法）
             */
            return method.invoke(target, args);
        }
    }
}

